<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 包裹列表内容 -->
    <el-card class="box-card">
      <!-- 布局容器 -->
      <el-row :gutter="20">
            <!-- 搜索栏 -->
        <search @funQuery='search'></search>
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <!-- 按钮 -->
            <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
            <!-- 点击添加按钮弹出对话框 -->
            <el-dialog
              title="添加用户"
              :visible.sync="dialogVisible"
              width="70%"
              @close="addDialogClosed"
            >
              <!-- 添加的内容 -->
              <el-form
                :model="addUserForm"
                ref="addUserRef"
                label-width="100px"
                class="demo-ruleForm"
                :rules="rules"
              >
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="addUserForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input v-model="addUserForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="addUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                  <el-input v-model="addUserForm.mobile"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
              </span>
            </el-dialog>
          </div>
        </el-col>
      </el-row>
      <!-- 表格  存放用户列表 -->
      <el-table :data="tableData" style="width: 100%" stripe border>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="condition(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-row>
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                size="mini"
                @click="editUser(scope.row)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                size="mini"
                @click="delUser(scope.row.id)"
              ></el-button>
              <el-button
                type="warning"
                icon="el-icon-s-tools"
                circle
                size="mini"
                @click="deployUser(scope.row)"
              ></el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
      <!-- 点击编辑按钮弹出对话框 -->
      <el-dialog title="修改用户" :visible.sync="editUserVisible" width="70%" @close="editDialogClosed">
        <!-- 需要修改的内容 -->
        <el-form
          :model="editUserForm"
          ref="editUserRef"
          label-width="100px"
          class="demo-ruleForm"
          :rules="rules"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editUserForm.username" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editUserVisible = false">取 消</el-button>
          <el-button type="primary" @click="getEditIdUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 点击设置按钮弹出对话框 -->
      <el-dialog
        title="分配用户"
        :visible.sync="deployUserVisible"
        width="70%"
        @close="deployDialogClosed"
      >
        <!-- 需要修改的内容 -->
        <el-form
          :model="deployUserForm"
          ref="deployUserRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="当前的用户:" prop="username">
            <span>{{deployUserForm.username}}</span>
          </el-form-item>
          <el-form-item label="当前的角色:" prop="roleName">
            <span>{{deployUserForm.roleName}}</span>
          </el-form-item>
          <el-form-item label="分配新角色:" prop="roleNameList">
            <!-- 选择器 -->
            <el-select v-model="roleId" placeholder="请选择">
              <el-option
                v-for="item in deployUserForm.roleNameList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
                :clearable='true'
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="deployUserVisible = false">取 消</el-button>
          <el-button type="primary" @click='addRolesUser'>确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
           
<script>
import search from '@/components/common/search.vue'
import {
  authorityUser,
  usersList,
  getCondition,
  getAddUserForm,
  getDelUserForm,
  getEditUserForm,
  getRolesUserForm
} from "@/api";
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb();
      }

      cb(new Error("请输入合法的邮箱"));
    };

    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

      if (regMobile.test(value)) {
        return cb();
      }

      cb(new Error("请输入合法的手机号"));
    };
    return {
      // 添加用户
      addUserForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 修改用户
      editUserForm: {
        username: "",
        email: "",
        mobile: ""
      },
      // 分配权限
      deployUserForm: {
        userId: '',
        username: "",
        roleName: "",
        roleNameList: []
      },
      //选择角色的id
      roleId: '',
      // 规则设置
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6 到 11 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      //页面渲染
      tableData: [],
      //第几页
      currentPage: 1,
      //显示条数
      pagesize: 5,
      //总条数
      total: 0,
      //搜索框中内容
      query: "",
      //点击添加按钮页面是否显示
      dialogVisible: false,
      //点击修改按钮页面是否显示
      editUserVisible: false,
      //点击设置按钮页面是否显示
      deployUserVisible: false,
      //存储需要修改用户的Id
      userId: ""
    };
  },
  methods: {
    //获取user列表信息
    async getUserList() {
      var { data: res } = await usersList({
        query: this.query,
        pagenum: this.currentPage,
        pagesize: this.pagesize
      });
      this.tableData = res.data.users;
      // console.log(res,99);
      this.total = res.data.total;
    },
    // 用户状态功能
    async condition(data) {
      var { data: res } = await getCondition({
        id: data.id,
        type: data.mg_state
      });
      // console.log(res,99);
      if (res.meta.status !== 200)
        return this.$message.error("更新用户状态失败！");
      this.$message.success("用户状态更新成功！");
    },
    //分页
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pagesize = val;
      this.getUserList();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.getUserList();
    },
    // 搜索
    search(val) {
      console.log(val,99);
      
      this.query = val;
      this.getUserList();
    },
    //点击添加关闭按钮
    addDialogClosed() {
      this.$refs.addUserRef.resetFields();
    },
    //点击编辑关闭按钮
    editDialogClosed() {
      this.$refs.editUserRef.resetFields();
    },
    //点击设置关闭按钮
    deployDialogClosed() {
      this.$refs.deployUserRef.resetFields();
      // console.log(this.$refs,888);
    },
    //点击确认添加用户功能
    addUser() {
      this.$refs.addUserRef.validate(async valid => {
        if (!valid) return;
        var { data: res } = await getAddUserForm(this.addUserForm);
        if (res.meta.status !== 201)
          return this.$message.error("添加用户失败！");
        this.getUserList();
      });
    },
    //删除用户
    async delUser(id) {
      var state = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
      // console.log(aa);
      if (state == "confirm") {
        var { data: res } = await getDelUserForm(id);
        console.log(res);
        if (res.meta.status !== 200) return this.$message.error("删除失败");
        this.$message.success("删除成功");
        this.getUserList();
      }
    },
    //修改用户
    editUser(params) {
      this.userId = params.id;
      console.log(params);
      this.editUserVisible = true;
      this.editUserForm.username = params.username;
      this.editUserForm.email = params.email;
      this.editUserForm.mobile = params.mobile;
    },
    // 点击修改
    async getEditIdUser() {
      // console.log(this.userId,99);
      // console.log(this.editUserForm);
      var { data: res } = await getEditUserForm(this.userId, this.editUserForm);
      console.log(res);
      this.getUserList();
      this.editUserVisible = false;
    },
    // 给用户分配角色功能
    async deployUser(data) {
      // console.log(data,999);
      this.deployUserForm.userId = data.id;
      this.deployUserForm.username = data.username;
      this.deployUserForm.roleName = data.role_name;
      // 获取角色列表
      var { data: res } = await authorityUser();
      // console.log(res, 9999);
      this.deployUserForm.roleNameList = res.data;
      this.deployUserVisible = true;
    },
    //点击确认按钮 确定分配角色功能
    async addRolesUser(){
      // console.log(this.deployUserForm.userId,778);
      console.log(this.roleId,77);
      var {data:res} = await getRolesUserForm(this.deployUserForm.userId,this.roleId);
      console.log(res);
    }
  },
  // 生命周期
  created() {
    this.getUserList();
  },
  components: {
    search
  }
};
</script>
<style scoped>
.el-breadcrumb {
  margin-bottom: 15px;
}
.el-table {
  margin-top: 15px;
}
</style>